package com.dhcc.sds.standard.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.standard.dao.SdsStandRuleBaseMapper;
import com.dhcc.sds.standard.entity.SdsStandRuleBaseEntity;
import com.dhcc.sds.standard.service.ISdsStandRuleBaseService;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("sdsStandRuleBaseService")
public class SdsStandRuleBaseServiceImpl extends BaseServiceImpl<SdsStandRuleBaseMapper, SdsStandRuleBaseEntity> implements ISdsStandRuleBaseService {

    @Override
    public List<SdsStandRuleBaseEntity> page(Page<SdsStandRuleBaseEntity> page, Map<String, Object> params) {
        return this.baseMapper.page(page, params);
    }

    @Override
    public List<SdsStandRuleBaseEntity> selectDisplayRule(Map<String, Object> params) {
        List<SdsStandRuleBaseEntity> res = new ArrayList<>();
        String compare = (String) params.get("compare");
        String displayRule = "";
        if (CommonUtil.equals(compare, "all")) {
            res = this.baseMapper.list(params);
        } else {
            if (CommonUtil.isNotEmpty(params.get("displayRule"))) {
                try {
                    displayRule = java.net.URLDecoder.decode((String) params.get("displayRule"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                List<String> list = handleRuleExpressions(displayRule);
                res = this.baseMapper.selectDisplayRule(list);
            }
        }
        return res;
    }

    private List<String> handleRuleExpressions(String showPremise) {
        //小括号及其里面内容
        String p1 = "\\(.*?\\)";
        List<String> res = new ArrayList<>();
        Pattern p = Pattern.compile(p1);
        Matcher m = p.matcher(showPremise);
        while (m.find()) {
            String ruleExpression = m.group().substring(1, m.group().length() - 1);
            res.add(ruleExpression);
        }
        return res;
    }
    @Override
    public String getMaxCode(){
        return this.baseMapper.getMaxCode();
    }
}
